package com.hoppi;

/**
 * <p>
 * 创建日期：2021-07-30 22:39
 *
 * @author Hoppinging
 * @version 1.1
 * @since 1.0
 */
public class MyLinkedStack<E> {
    private int length;
    private Node<E> head;
    public MyLinkedStack() {
        length = 0;
        head = new Node<>();
        head.next = null;
    }

    public MyLinkedStack(E element) {
        length = 1;
        head = new Node<>(element);
        head.next =null;
    }

    public synchronized void push(E element) {
        if(length == 0){
            head.setData(element);
        }else {
            Node<E> node = new Node<>(element);
            node.next = head;
            head = node;
        }
        length++;
    }
    static class PopException extends Throwable{
        public PopException() {
            System.out.println("Pop failed, the stack is empty.");
        }
    }
    public synchronized E pop() throws PopException {
        if(length == 0) {
            throw new PopException();
        }else{
            Node<E> temp;
            temp = head;
            head = head.next;
            length --;
            return temp.getData();
        }
    }
    public void print() {
        Node<E> index = head;
        while(index.next != null){
            index.print();
            index = index.next;
        }
    }
    public void printTop() {
        if(length == 0) {
            System.out.println("The stack is empty.");
        }else{
            head.print();
        }
    }
    public boolean isEmpty() {
        return length == 0;
    }
    public int getLength() {
        return length;
    }
}
class Node<E> {
    private E data;
    Node<E> next;

    public Node() {
    }

    public Node(E data) {
        this.data = data;
    }

    public void print() {
        System.out.println(this.data.toString());
    }

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }
}